<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
class Product_model extends MY_Model {
	var $table = 'sm_warehouse_stock';
	
	public function __construct() {
		parent::__construct ();
	}
	/**
	 * 获取缓存的商品信息
	 * 
	 * @param number $address_id
	 * @param boolean $isHot
	 * @return array
	 */
	public function getProduct($address_id, $isHot=false) {
		
		if(empty($address_id)) {
			return NULL;
		}
		
		if($isHot) {
			$select = 'a1.img as imgHot';
		} else {
			$select = '';
		}
		
		$this->db
		->select ( 'sws.id,sws.address_id,sws.product_id,sws.stock,sws.sold_out,p.category_id,p.name productName,format(p.price/100, 2) price,format(p.market_price/100, 2) market_price,p.specs,p.isHot,p.isLimit,p.limit_num,a.img,'.$select, false )
		->from ( $this->table . ' sws' )
		->join('branch_assignment ba', 'sws.address_id=ba.warehouse_address_id', 'left')
		->join('product p', 'sws.product_id=p.id', 'left')
		->join('album a', 'p.thumbnail_id=a.id', 'left')
		->where(array('ba.address_id'=>$address_id, 'sws.status'=>  REST_Controller::STATUS_ACTIVE, 'sws.stock >'=>  REST_Controller::STATUS_DELETE))
		->group_by('sws.id')
		->order_by('p.rank desc,sws.sold_out desc,sws.id desc');
				
		if($isHot) {
			$this->db->where(array('p.isHot'=>'10'));
			$this->db->join('album a1', 'p.hot_img_id=a1.id', 'left');
		}
		
		$query = $this->db->get ();		
		$data = $query->result_array ();
		if(!empty($data)) {
			$ids = array();
			$limitIds = array();
			foreach ($data as &$v) {
				$ids[] = $v['id'];
				if($v['isLimit']) {
					$limitIds[$v['id']] = $v['limit_num'];
				}
				$v['img'] = empty($v['img']) ? '' : base_url($v['img']);
				if(isset($v['imgHot'])) {
					$v['imgHot'] = empty($v['imgHot']) ? '' : base_url($v['imgHot']);
				}
			}
			if(isset($_SESSION)) {
				$data = $this->my_array_merge($data, $this->getLimitProduct($limitIds));
			}
		}
		return $data;
	}
	/**
	 * 获取变化的商品信息
	 * @param array $ids
	 */
	private function getLimitProduct($ids) {
		$data = array();
		if (!empty($ids) && is_array($ids)) {
			$query = $this->db
			->select('od.sw_product_id id, sum(`od`.`number`) limit_num')
			->from('order_details od')
			->join('order o', 'od.order_id=o.id','left')
			->where_in('od.sw_product_id', array_keys($ids))
			->where(array('user_id'=>$_SESSION['uid']))
			->group_by('od.sw_product_id')
			->get();
			$data = $query->result_array();
			if(!empty($data)) {
				foreach ($data as &$v) {
					$sub = $ids[$v['id']]-$v['limit_num'];
					$v['limit_num'] = $sub > 0 ? $sub:0;
				}
			}
		}
		return $data;		
	}
	/**
	 * 从库存中减去订单请求数
	 * @param array $order
	 * @throws Exception
	 */
	public function reduce($order) {
		foreach ($order as $v) {
			$this->db->set('stock', "stock-{$v['request_num']}", FALSE);
			$this->db->where(array('id'=>$v['id'], 'stock >='=>$v['request_num']));
			$this->db->update($this->table . ' sws');
			if($this->db->affected_rows() !== 1) {
				throw new Exception();
			}
		}

	}
	public function updateSoldOut($orderId) {
		$query = $this->db->select('sw_product_id as id, number')
				->from('order_details')
				->where(array('order_id'=>$orderId))
				->get();
		$rows = $query->result_array();
		if(!empty($rows)) {
			$this->db->trans_start();
			foreach ($rows as $v) {
				$this->db->set('sold_out', "sold_out+{$v['number']}", false);
				$this->db->where('id', $v['id']);
				$this->db->update($this->table . ' sws');
			}
			$this->db->trans_complete();
		}
	}
	private function my_array_merge(array $array1, array $_ = null) {
		$data = array();
		$tmp = array();
		if(!empty($_)) {
			foreach ($_ as $v) {
				$tmp[$v['id']] = $v;
			}
		}
		foreach ($array1 as $k=>$v) {
			if(isset($tmp[$v['id']]) && $v['id'] == $tmp[$v['id']]['id']) {
				$v = array_merge($v, $tmp[$v['id']]);
			}
			if(isset($v['img'])) {
				$v['img'] = base_url($v['img']);
			}
			$data[] = $v;
		}
		return $data;
	}
}